import os
import time
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import notify2
import pyperclip
from pathlib import Path

WATCH_DIR = Path("~/Pictures/Screenshots").expanduser()
TESSERACT_PATH = "tesseract"
OCR_LANGUAGE = "chi_sim+chi_tra+eng+deu" 


class ScreenshotHandler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory and event.src_path.lower().endswith(('.png', '.jpg', '.jpeg')):
            shot_path = Path(event.src_path)
            img_file = str(shot_path.absolute())
            ocr_txt = shot_path.parent.joinpath("ocr_output.txt")
            ocr_file = str(ocr_txt.with_suffix(""))
            print(str(shot_path.absolute()) + '\n' + str(ocr_txt.absolute()))
            time.sleep(1)  # 等文件写入完成
            subprocess.run([TESSERACT_PATH, img_file, ocr_file, "-l", OCR_LANGUAGE],
                   stdout=subprocess.DEVNULL,
                   stderr=subprocess.DEVNULL)

            with open(ocr_txt, "r", encoding="utf-8") as f:
                text = f.read().strip()

            pyperclip.set_clipboard("xclip")
            pyperclip.copy(text)  # 写入剪贴板
            notify2.init("OCR Notifier")
            n = notify2.Notification("OCR识别完成", text[:100] + '...' if len(text) > 100 else text)
            n.set_timeout(5000)
            n.show()

if __name__ == "__main__":
    event_handler = ScreenshotHandler()
    observer = Observer()
    observer.schedule(event_handler, WATCH_DIR, recursive=False)
    observer.start()
    print(f"监控中：{WATCH_DIR}")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

